package com.sduept.nwld.dataserver.controller.equipment.assessment;

import com.sduept.bigdata.equipment.assessment.model.hiddendanger.track.RectificationPlan;
import com.sduept.bigdata.equipment.assessment.model.inspection.InspectionExpert;
import com.sduept.bigdata.equipment.assessment.model.inspection.InspectionPlan;
import com.sduept.bigdata.equipment.assessment.service.InspectionExpertService;
import com.sduept.bigdata.equipment.assessment.service.InspectionPlanService;
import com.sduept.bigdata.equipment.assessment.service.RectificationPlanService;
import com.sduept.bigdata.web.jsf.controller.AbstractController;
import com.sduept.utils.DateUtil;
import com.sduept.utils.PingYinUtil;
import org.apache.commons.lang3.StringUtils;
import org.primefaces.event.SelectEvent;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import java.util.*;

/**
 * 整改计划controller类
 */
@Named
@ViewScoped
public class RectificationPlanController extends AbstractController {
	
	private static final long serialVersionUID = 5233283549395529450L;
	
	@Autowired
	private RectificationPlanService service;
	@Autowired
	private InspectionPlanService planSerivce;
	@Autowired
	private InspectionExpertService expertService;
	/**
	 * 所有的计划
	 */
	private List<InspectionPlan> inspectionPlans = null;
	
	/**
	 * 页面所展示的整改计划
	 */
	private List<RectificationPlan> allRectificationPlans = null;
	/**
	 * 查询下拉框的所有专家
	 */
	private List<InspectionExpert> experts = null;
	
	private RectificationPlan selected;
	
	/**
	 * 查询条件
	 */
	private RectificationPlan queryParam = new RectificationPlan();
	
	@PostConstruct
	public void init() {
		allRectificationPlans = service.findAll();
		experts = expertService.findAll();
		inspectionPlans = planSerivce.findAll();
	}

	
	/**
	 * 根据计划名称查询
	 * @param query
	 * @return
	 */
	public List<String> completePlan(String query) {
		Set<String> result = new LinkedHashSet<String>();
		result.add("全部");
		for (InspectionPlan plan : inspectionPlans) {
			String nameHead = PingYinUtil.getPingYinHeader(plan.getName());
			if (nameHead.toLowerCase().contains(query)) {
				result.add(plan.getName());
			}
			if (plan.getName().contains(query)) {
				result.add(plan.getName());
			}
		}
		return new ArrayList<String>(result);
	}

	/**
	 * 被检变电站集合
	 * @param query
	 * @return
	 */
	public List<String> completeStation(String query) {
		Set<String> stations = new LinkedHashSet<String>();
		stations.add("全部");
		for (RectificationPlan rp : allRectificationPlans) {
			String stationName = rp.getStationName();
			if(StringUtils.isNotBlank(stationName)) {
				String nameHead = PingYinUtil.getPingYinHeader(stationName);
				if (nameHead.toLowerCase().contains(query)) {
					stations.add(stationName);
				}
				if (stationName.contains(query)) {
					stations.add(stationName);
				}
			}
		}
		return new ArrayList<String>(stations);
	}
	
	/**
	 * 专家在输入框的显示
	 * @param query
	 * @return
	 */
	public List<String> completeExpert(String query) {
		Set<String> names = new HashSet<String>();
		for (InspectionExpert expert : experts) {
			String nameHead = PingYinUtil.getPingYinHeader(expert.getName());
			if (nameHead.toLowerCase().contains(query)) {
				names.add(expert.getName());
			}
			if (expert.getName().contains(query)) {
				names.add(expert.getName());
			}
		}
		return new ArrayList<String>(names);
	}
	
	/**
	 * 查询
	 */
	public void query() {
		try {
			allRectificationPlans = service.findByCondition(getQueryConditions(queryParam));
		} catch (Exception e) {
			addErrorMessage("查询失败！");
			e.printStackTrace();
		}
	}
	
	/**
	 * 重置
	 */
	public void resetQuery() {
		queryParam = new RectificationPlan();
		allRectificationPlans = service.findAll();
	}
	
	private Map<String,Object[]> getQueryConditions(RectificationPlan rp) {
		Map<String,Object[]> map = new HashMap<String, Object[]>();
		StringBuilder builder = new StringBuilder(" 1=1 ");
		List<Object> args = new ArrayList<Object>();
		if(StringUtils.isNotBlank(rp.getStationName()) && !rp.getStationName().equals("全部")) {//变电站
			builder.append(" and stationName =? ");
			args.add(rp.getStationName());
		}
		if(StringUtils.isNotBlank(rp.getInspectionPlanName()) && !rp.getInspectionPlanName().equals("全部")) {
			builder.append(" and inspectionPlanName = ?");
			args.add(rp.getInspectionPlanName());
		}
		if(rp.getStatus()!=null) {//是否完成
			builder.append(" and status =? ");
			args.add(rp.getStatus());
		}
		if(rp.getVoltage()!=null) {
			if(rp.getVoltage().toString().equals("499")) {
				builder.append(" and voltage >? ");
				args.add(rp.getVoltage());
			} else if(rp.getVoltage().toString().equals("221")) {
				builder.append(" and voltage <=? ");
				args.add(rp.getVoltage());
			} 
		}
		if(StringUtils.isNotBlank(rp.getInspectionExpertName())) {//专家名
			builder.append(" and inspectionExpertName =? ");
			args.add(rp.getInspectionExpertName());
		}
		if((rp.getPlanStartDate() != null || rp.getPlanFinishDate() != null)) {//完成时间
			if(rp.getPlanStartDate() ==null) {
				builder.append(" and actualFinishDate <= ?");
				String s1 = DateUtil.getStringDate(rp.getPlanFinishDate(), DateUtil.pattern_ymd) + " 00:00:00";
				Date end = DateUtil.getDateByString(s1, DateUtil.pattern_ymdhms);//开始时间
				args.add( end);
			} else if(rp.getPlanFinishDate()==null) {
				builder.append(" and actualFinishDate >= ?");
				String s1 = DateUtil.getStringDate(rp.getPlanStartDate(), DateUtil.pattern_ymd) + " 00:00:00";
				Date start = DateUtil.getDateByString(s1, DateUtil.pattern_ymdhms);//开始时间
				args.add(start);
				
			} else {
				builder.append(" and actualFinishDate between ? and ? ");
				args.add(rp.getPlanStartDate());
				args.add(rp.getPlanFinishDate());
			}
		}
		String sql = builder.toString();
		map.put(sql, args.toArray());
		return map;
	}
	
	public void onRowSelect(SelectEvent event) {
		selected = (RectificationPlan) event.getObject();
	}
	
	public void delete() {
		if(null != selected) {
			try {
				service.deleteById(selected.getId());
				allRectificationPlans.remove(selected);
			} catch (Exception e) {
				e.printStackTrace();
				addErrorMessage("删除失败");
			}
		}
		addSuccessMessage("删除成功！");
		selected = null;
	}
	
	/**
	 *	整改时间前【15天】：蓝色提示；
	 * 	整改时间前【10天】：黄色提示；
	 * 	整改时间前【5天】：红色提示；
	 * @param track
	 * @return
	 */
	public String getRowClass(RectificationPlan rp) {
		String bgColor = "blank";
		if(null == rp) {
			return bgColor;
		}
		Date planStartDate = rp.getPlanStartDate();
		Integer days = differentDays(new Date(),planStartDate);
		if(null == days) {
			return bgColor;
		}
		if(days<=5) {
			bgColor = "red";
		} else if (days<=10) {
			bgColor = "yellow";
		} else if (days<=15) {
			bgColor = "blue";
		}
		return bgColor;
	}
	
	/**
	 * 判断两个时间相差的天数
	 * @param minDate
	 * @param maxDate
	 * @return
	 */
	private Integer differentDays(Date minDate,Date maxDate) {
		if(null == minDate || null == maxDate) {
			return null;
		}
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(minDate);
        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(maxDate);
        int day1= cal1.get(Calendar.DAY_OF_YEAR);
        int day2 = cal2.get(Calendar.DAY_OF_YEAR);
        int year1 = cal1.get(Calendar.YEAR);
        int year2 = cal2.get(Calendar.YEAR);
        if(year1 != year2) {  //同一年
            int timeDistance = 0 ;
            for(int i = year1 ; i < year2 ; i ++) {
                if(i%4==0 && i%100!=0 || i%400==0) {
                	//	闰年
                    timeDistance += 366;
                } else {
                	//不是闰年
                    timeDistance += 365;
                }
            }
            return timeDistance + (day2-day1) ;
        } else {
        	//不同年
            return day2-day1;
        }
    }
	
	
	public List<RectificationPlan> getAllRectificationPlans() {
		return allRectificationPlans;
	}


	public void setAllRectificationPlans(List<RectificationPlan> allRectificationPlans) {
		this.allRectificationPlans = allRectificationPlans;
	}


	public RectificationPlan getSelected() {
		return selected;
	}


	public void setSelected(RectificationPlan selected) {
		this.selected = selected;
	}


	public RectificationPlan getQueryParam() {
		return queryParam;
	}


	public void setQueryParam(RectificationPlan queryParam) {
		this.queryParam = queryParam;
	}
	
}
